<template>
	<view class="page login-page">
		<!-- 自定义导航栏 -->
		<ob-navbar 
			title="登录" 
			:show-back="true" 
			background-color="rgba(255, 255, 255, 0.95)"
			title-color="#333333"
			:border="true"
			:prevent-default-back="true"
			@left-click="handleBackToHome"
		/>
		
		<view class="login-container">
			<!-- Logo区域 -->
			<view class="logo-section">
				<view class="ship-container">
					<image src="/static/images/ship.svg" class="ship-image" mode="aspectFit"></image>
				</view>
				<text class="app-name">OceanBridge</text>
				<text class="app-slogan">连接海洋，桥接世界</text>
			</view>
			
			<!-- 登录表单 -->
			<view class="form-section">
				<view class="form-item">
					<view class="input-wrapper">
						<text class="input-icon">📧</text>
						<input 
							v-model="formData.account"
							type="text" 
							placeholder="请输入邮箱或用户名"
							class="form-input"
							@blur="validateAccount"
						/>
					</view>
					<text v-if="errors.account" class="error-text">{{ errors.account }}</text>
				</view>
				
				<view class="form-item">
					<view class="input-wrapper">
						<text class="input-icon">🔒</text>
						<input 
							v-model="formData.password"
							:type="passwordVisible ? 'text' : 'password'"
							placeholder="请输入密码"
							class="form-input"
							@blur="validatePassword"
						/>
						<text 
							class="password-toggle" 
							@click="togglePasswordVisible"
						>
							{{ passwordVisible ? '👁️' : '👁️‍🗨️' }}
						</text>
					</view>
					<text v-if="errors.password" class="error-text">{{ errors.password }}</text>
				</view>
				
				<!-- 记住密码和忘记密码 -->
				<view class="form-options">
					<label class="checkbox-wrapper" @click="toggleRememberPassword">
						<text class="checkbox" :class="{ 'checkbox--checked': formData.rememberPassword }">
							{{ formData.rememberPassword ? '✓' : '' }}
						</text>
						<text class="checkbox-text">记住密码</text>
					</label>
					<text class="forgot-password" @click="goToResetPassword">忘记密码？</text>
				</view>
				
				<!-- 登录按钮 -->
				<button
					class="btn btn-primary btn-large login-btn"
					:class="{ 'btn--loading': isLoading }"
					:disabled="isLoading || !isFormValid"
					@click="handleLogin"
				>
					<text v-if="isLoading">登录中...</text>
					<text v-else>登录</text>
				</button>

				<!-- 其他登录方式 -->
				<view class="alternative-login">
					<view class="divider">
						<view class="divider-line"></view>
						<text class="divider-text">其他登录方式</text>
						<view class="divider-line"></view>
					</view>

					<view class="alternative-buttons">
						<button class="btn btn-face face-login-btn" @click="goToFaceLogin">
							<text class="btn-icon">👤</text>
							<text>人脸登录</text>
						</button>
					</view>
				</view>

				<!-- 注册链接 -->
				<view class="register-link">
					<text class="register-text">还没有账号？</text>
					<text class="register-action" @click="goToRegister">立即注册</text>
					<text class="register-text"> | </text>
					<text class="register-action" @click="goToFaceRegister">人脸注册</text>
				</view>
			</view>
			
		</view>
		
		<!-- 加载提示 -->
		<ob-loading :visible="isLoading" text="登录中..." />
	</view>
</template>

<script setup>
import { ref, reactive, computed, inject } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import authApi from '../../api/auth.js'
import { validateEmail } from '../../utils/common.js'

// 注入状态管理
const store = inject('$store')

// 响应式数据
const isLoading = ref(false)
const passwordVisible = ref(false)

const formData = reactive({
	account: '',
	password: '',
	rememberPassword: false
})

const errors = reactive({
	account: '',
	password: ''
})

// 计算属性
const isFormValid = computed(() => {
	return formData.account.trim() !== '' && 
	       formData.password.trim() !== '' && 
	       !errors.account && 
	       !errors.password
})

// 生命周期
onLoad((options) => {
	// 检查是否需要自动填充账号
	const rememberedAccount = uni.getStorageSync('rememberedAccount')
	if (rememberedAccount) {
		formData.account = rememberedAccount
		formData.rememberPassword = true
	}
	// 如果从注册/验证页面跳转过来，自动填充邮箱
	if (options.email) {
		formData.account = decodeURIComponent(options.email)
		formData.rememberPassword = true
	}
})

// 方法
const validateAccount = () => {
	errors.account = ''
	
	if (!formData.account.trim()) {
		errors.account = '请输入邮箱或用户名'
		return false
	}
	
	// 如果包含@符号，验证邮箱格式
	if (formData.account.includes('@')) {
		if (!validateEmail(formData.account)) {
			errors.account = '请输入正确的邮箱格式'
			return false
		}
	} else {
		// 验证用户名格式
		if (formData.account.length < 3) {
			errors.account = '用户名至少3个字符'
			return false
		}
	}
	
	return true
}

const validatePassword = () => {
	errors.password = ''
	
	if (!formData.password.trim()) {
		errors.password = '请输入密码'
		return false
	}
	
	if (formData.password.length < 6) {
		errors.password = '密码至少6个字符'
		return false
	}
	
	return true
}

const togglePasswordVisible = () => {
	passwordVisible.value = !passwordVisible.value
}

const toggleRememberPassword = () => {
	formData.rememberPassword = !formData.rememberPassword
}

const handleLogin = async () => {
	// 验证表单
	if (!validateAccount() || !validatePassword()) {
		return
	}
	
	isLoading.value = true
	
	try {
			const loginData = {
		usernameOrEmail: formData.account.trim(),
		password: formData.password
	}
	
	const response = await authApi.login(loginData)
	
	// 登录成功，保存token和用户信息
	const { accessToken, refreshToken, userId, username } = response
	
	// 构建用户信息对象
	const userInfo = {
		id: userId,
		username: username,
		email: formData.account.includes('@') ? formData.account : '',
		emailVerified: true
	}
	
	// 保存用户信息和token到状态管理
	store.actions.login(userInfo, accessToken, refreshToken)
		
		// 记住密码
		if (formData.rememberPassword) {
			uni.setStorageSync('rememberedAccount', formData.account)
		} else {
			uni.removeStorageSync('rememberedAccount')
		}
		
		uni.showToast({
			title: '登录成功',
			icon: 'success',
			duration: 1500
		})
		
		// 获取完整的用户信息
		try {
			const profileResponse = await authApi.getProfile()
			if (profileResponse) {
				// 更新用户信息
				store.actions.setUserInfo({
					...userInfo,
					...profileResponse
				})
			}
		} catch (profileError) {
			console.warn('获取用户信息失败:', profileError)
			// 不影响登录流程，使用基本信息继续
		}
		
		// 直接进入首页（取消邮箱验证提示）
		goToHome()
		
	} catch (error) {
		console.error('登录失败:', error)
		// 处理特定的错误情况
		let errorMessage = '登录失败，请重试'
		if (error.message) {
			if (error.message.includes('401') || error.message.includes('未授权')) {
				errorMessage = '用户名或密码错误'
			} else if (error.message.includes('邮箱未验证')) {
				// 引导去邮箱验证页
				uni.showModal({
					title: '邮箱未验证',
					content: '您的邮箱尚未验证，是否前往验证？',
					confirmText: '去验证',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: `/pages/auth/email-verify?email=${encodeURIComponent(formData.account)}`
							})
						}
					}
				})
				return
			} else {
				errorMessage = error.message
			}
		}
		
		uni.showToast({
			title: errorMessage,
			icon: 'none',
			duration: 2000
		})
	} finally {
		isLoading.value = false
	}
}


const goToHome = () => {
	// 直接进入首页（不强制选择目的港）
	uni.switchTab({
		url: '/pages/index/index'
	})
}

const goToRegister = () => {
	uni.navigateTo({
		url: '/pages/auth/register'
	})
}

const goToFaceLogin = () => {
	uni.navigateTo({
		url: '/pages/auth/face-login'
	})
}

const goToFaceRegister = () => {
	uni.navigateTo({
		url: '/pages/auth/face-register'
	})
}

const goToResetPassword = () => {
	uni.navigateTo({
		url: '/pages/auth/forgot-password'
	})
}

const handleBackToHome = () => {
	uni.reLaunch({
		url: '/pages/index/index'
	})
}



</script>

<style lang="scss" scoped>
.login-page {
	min-height: 100vh;
	background: #ffffff;
	position: relative;
	overflow: hidden;
	
	
	.login-container {
		padding: 40px 30px 30px;
		min-height: calc(100vh - 88px);
		display: flex;
		flex-direction: column;
		position: relative;
		z-index: 10;
	}
	
	.logo-section {
		text-align: center;
		margin-bottom: 60px;
		padding: 25px 20px;
		background: rgba(0, 0, 0, 0.03);
		backdrop-filter: blur(15px);
		border-radius: 20px;
		border: 2px solid rgba(0, 0, 0, 0.15);
		box-shadow: 
			0 6px 24px rgba(0, 0, 0, 0.05),
			inset 0 1px 0 rgba(255, 255, 255, 0.8);
		
		.ship-container {
			width: 100px;
			height: 80px;
			margin: 0 auto 16px;
			display: flex;
			align-items: center;
			justify-content: center;
			animation: shipFloat 3s ease-in-out infinite;
		}
		
		.ship-image {
			width: 80px;
			height: 60px;
			filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.1));
		}
		
		.app-name {
			display: block;
			font-size: 28px;
			font-weight: 700;
			color: var(--text-color);
			margin-bottom: 8px;
		}
		
		.app-slogan {
			display: block;
			font-size: 16px;
			color: var(--text-secondary);
			font-weight: 300;
			letter-spacing: 0.5px;
		}
	}
	
	
	.form-section {
		flex: 1;
		
		.form-item {
			margin-bottom: 24px;
		}
		
		.input-wrapper {
			position: relative;
			display: flex;
			align-items: center;
			background: rgba(255, 255, 255, 0.95);
			backdrop-filter: blur(10px);
			border-radius: 16px;
			padding: 0 20px;
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
			border: 1px solid rgba(0, 0, 0, 0.1);
			transition: all 0.3s ease;
			
			&:hover {
				background: rgba(255, 255, 255, 1);
				box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
			}
			
			&:focus-within {
				background: rgba(255, 255, 255, 1);
				box-shadow: 0 4px 16px rgba(0, 122, 255, 0.2);
				border-color: var(--primary-color);
			}
		}
		
		.input-icon {
			font-size: 20px;
			margin-right: 12px;
		}
		
		.form-input {
			flex: 1;
			height: 56px;
			font-size: 16px;
			color: var(--text-color);
			border: none;
			background: transparent;
			transition: all 0.3s ease;
			
			&::placeholder {
				color: var(--text-placeholder);
				transition: color 0.3s ease;
			}
			
			&:focus {
				outline: none;
				
				&::placeholder {
					color: rgba(153, 153, 153, 0.5);
				}
			}
		}
		
		.password-toggle {
			font-size: 20px;
			padding: 8px;
			cursor: pointer;
			transition: all 0.3s ease;
			border-radius: 6px;
			
			&:hover {
				background: rgba(0, 122, 255, 0.1);
				transform: scale(1.1);
			}
			
			&:active {
				transform: scale(0.95);
			}
		}
		
		.error-text {
			display: block;
			color: var(--error-color);
			font-size: 12px;
			margin-top: 8px;
			margin-left: 16px;
		}
		
		.form-options {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 32px;
		}
		
		.checkbox-wrapper {
			display: flex;
			align-items: center;
		}
		
		.checkbox {
			width: 20px;
			height: 20px;
			border: 2px solid rgba(0, 0, 0, 0.2);
			border-radius: 6px;
			margin-right: 10px;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 12px;
			color: #ffffff;
			background: rgba(0, 0, 0, 0.05);
			backdrop-filter: blur(5px);
			transition: all 0.3s ease;
			
			&--checked {
				background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
				border-color: var(--primary-color);
				color: #ffffff;
				box-shadow: 0 4px 12px rgba(0, 122, 255, 0.4);
			}
		}
		
		.checkbox-text {
			color: var(--text-color);
			font-size: 14px;
		}
		
		.forgot-password {
			color: var(--primary-color);
			font-size: 14px;
			text-decoration: underline;
		}
		
		.login-btn {
			width: 100%;
			margin-bottom: 24px;
			background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
			border: none;
			border-radius: 16px;
			box-shadow: 0 6px 20px rgba(0, 122, 255, 0.3);
			transition: all 0.3s ease;
			position: relative;
			overflow: hidden;
			
			&:hover {
				transform: translateY(-2px);
				box-shadow: 0 8px 24px rgba(0, 122, 255, 0.4);
			}
			
			&.btn--loading {
				opacity: 0.8;
				transform: none;
			}
		}
		
		
		.alternative-login {
			margin-bottom: 24px;
		}

		.divider {
			display: flex;
			align-items: center;
			margin-bottom: 20px;
		}

		.divider-line {
			flex: 1;
			height: 1px;
			background: rgba(0, 0, 0, 0.1);
		}

		.divider-text {
			padding: 0 16px;
			font-size: 14px;
			color: var(--text-secondary);
		}

		.alternative-buttons {
			display: flex;
			justify-content: center;
		}

		.btn-face {
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			color: #ffffff;
			border: none;
			border-radius: 16px;
			padding: 12px 24px;
			font-size: 14px;
			font-weight: 600;
			display: flex;
			align-items: center;
			gap: 8px;
			box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
			transition: all 0.3s ease;

			&:hover {
				transform: translateY(-2px);
				box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
			}
		}

		.register-link {
			text-align: center;
		}

		.register-text {
			color: var(--text-secondary);
			font-size: 14px;
		}

		.register-action {
			color: var(--primary-color);
			font-size: 14px;
			font-weight: 600;
			margin-left: 8px;
			text-decoration: underline;
		}
	}
	
	
	// 船浮动动画
	@keyframes shipFloat {
		0%, 100% {
			transform: translateY(0px) rotate(0deg);
		}
		25% {
			transform: translateY(-3px) rotate(1deg);
		}
		50% {
			transform: translateY(-5px) rotate(0deg);
		}
		75% {
			transform: translateY(-3px) rotate(-1deg);
		}
	}
	
	// 淡入上升动画
	@keyframes slideInUp {
		from {
			opacity: 0;
			transform: translateY(30px);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
	
}
</style>